package org.jeecg.modules.factor.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;


import org.jeecg.modules.api.DTO.CirsEmissionFactorDTO;
import org.jeecg.modules.api.DTO.EmissionFactorDTO;
import org.jeecg.modules.api.DTO.EmissionFactorQueryDTO;
import org.jeecg.modules.api.DTO.PrivateFactorQueryDTO;
import org.jeecg.modules.api.VO.EmissionFactorDescribeVO;
import org.jeecg.modules.api.VO.EmissionFactorQueryVO;
import org.jeecg.modules.api.VO.EmissionFactorVO;

import org.jeecg.modules.api.entity.*;
import org.jeecg.modules.factor.mapper.CyEmissionFactorCollectMapper;
import org.jeecg.modules.factor.mapper.CyEmissionFactorMapper;
import org.jeecg.modules.factor.mapper.CyHouseGasMapper;
import org.jeecg.modules.factor.service.ICyEmissionFactorDataService;
import org.jeecg.modules.factor.service.ICyEmissionFactorService;
import org.jeecg.modules.factor.service.ICyEmissionUnitService;
import org.jeecg.modules.gas.entity.CyGasStoreUnit;
import org.jeecg.modules.gas.mapper.CyGasStoreMapper;
import org.jeecg.modules.gas.mapper.CyGasStoreUnitMapper;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @Description: 碳排因子
 * @Author: jeecg-boot
 * @Date:   2024-11-01
 * @Version: V1.0
 */
@Service
public class CyEmissionFactorServiceImpl extends ServiceImpl<CyEmissionFactorMapper, CyEmissionFactor> implements ICyEmissionFactorService {

    @Autowired
    private CyEmissionFactorMapper cyEmissionFactorMapper;

    @Autowired
    private ISysBaseAPI sysBaseApi;

    @Autowired
    private CyEmissionFactorCollectMapper cyEmissionFactorCollectMapper;    //碳排因子收藏mapper

    @Autowired
    private ICyEmissionFactorDataService cyEmissionFactorDataService;      //碳排因子数据详情的service

    @Autowired
    private ICyEmissionUnitService cyEmissionUnitService;

    @Autowired
    private CyHouseGasServiceImpl cyHouseGasService;

    @Autowired
    private CyGasStoreMapper cyGasStoreMapper;    // 温室气体mapper

    @Autowired
    private CyGasStoreUnitMapper cyGasStoreUnitMapper;   //温室气体单位mapper

    @Autowired
    private RedisUtil redisUtil;

    public static String TOP_SEARCH_FACTOR = "topSearchFactor";    //redis中热门搜索因子的key

    public static String EACH_INDUSTRY_FACTOR_NUMBER = "eachIndustryFactorNumber";    //碳排因子库分页列表查询后，每个行业的因子数

    public static String HISTORY_RECORD = "historyRecord";    //碳排因子浏览记录

    public static String INDUSTRY_CATEGORY_PID = "1852194977303982081";    //碳排因子行业分类的pid

    public static String CO2E = "二氧化碳";

    /**
     *  修改发布状态
     *
     * @param id
     * @param state 发布状态
     * @return
     */
    @Override
    public void changeStatus(java.lang.String id, java.lang.String state) {
        //修改因子发布状态
        cyEmissionFactorMapper.changeStatus(id,state);
        // 只有修改为发布状态时才更新
        if(state.equals("1")){
            //获取当前用户
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            //获取当前用户名称
            String userName = sysUser.getUsername();
            //获取当前时间
            LocalDateTime now = LocalDateTime.now();
            //更细发布信息
            cyEmissionFactorMapper.updatePublishTime(id,userName,now);
        }
    }

    /**
     *  新增碳排因子
     *
     * @param emissionFactorDTO（包含碳排因子信息和碳排因子数据详情信息）
     * @param
     * @return
     */
    @Override
    @Transactional
    public void add(EmissionFactorDTO emissionFactorDTO) {

        CyEmissionFactor cyEmissionFactor = new CyEmissionFactor();    //碳排因子信息对象
        if(emissionFactorDTO != null){
            BeanUtils.copyProperties(emissionFactorDTO, cyEmissionFactor);
            cyEmissionFactor.setOrganizationId(emissionFactorDTO.getOrganizationId());
            cyEmissionFactor.setDeptId(emissionFactorDTO.getDeptId());
            // 如果是组织因子库，则发布状态设置为已发布
            if(emissionFactorDTO.getType().equals("2")){
                cyEmissionFactor.setState("1");
            }else{
            // 如果是碳排因子库，则发布状态设置为未发布
                cyEmissionFactor.setState("0");
            }
            cyEmissionFactor.setDelFlag(0);
        }
        //将数据插入碳排因子表中  (需要用到返回的id)
        cyEmissionFactorMapper.add(cyEmissionFactor);

        CyEmissionFactorData cyEmissionFactorData = new CyEmissionFactorData();  //碳排因子数据详情对象
        if(emissionFactorDTO != null){
            BeanUtils.copyProperties(emissionFactorDTO, cyEmissionFactorData);
            cyEmissionFactor.setOrganizationId(emissionFactorDTO.getOrganizationId());
            cyEmissionFactor.setDeptId(emissionFactorDTO.getDeptId());
            //碳排因子数据对象中的计算类型字段为type，而DTO对象中传递的计算类型为computerType
            cyEmissionFactorData.setType(emissionFactorDTO.getComputerType());
            //碳排因子数据详情对象与碳排因子关联起来
            cyEmissionFactorData.setEmissionFactorId(cyEmissionFactor.getId());
        }
        //将数据插入碳排因子数据详情表中
        cyEmissionFactorDataService.save(cyEmissionFactorData);

        //计算类型为配比计算，就存入气体对象
        if(cyEmissionFactorData.getType().equals("2") || emissionFactorDTO.getGasList().size() > 0 ){
            List<CyHouseGas> gasList = emissionFactorDTO.getGasList();
            for (CyHouseGas cyHouseGas : gasList) {
                //与碳排因子数据详情关联起来
                cyHouseGas.setEmissionFactorId(cyEmissionFactor.getId());
                //设置组织id和部门id
                cyHouseGas.setOrganizationId(emissionFactorDTO.getOrganizationId());
                cyHouseGas.setDeptId(emissionFactorDTO.getDeptId());
                cyHouseGasService.save(cyHouseGas);
            }
        }else{
            //如果为自动计算则默认增加一条二氧化碳的气体数据

            // 查询出二氧化碳这条气体数据
            CyGasStore cyGasStore = cyGasStoreMapper.selectGasByName(CO2E);

            // 碳排因子分子实际单位
            String realUnit = "";
            // 从碳排因子分子单位中获取到实际单位
            if(emissionFactorDTO.getNumeratorUnit().equals(CommonConstant.NUMERATOR_UNIT_T)){
                realUnit = CommonConstant.NUMERATOR_UNIT_T.substring(0,1);
            }else if(emissionFactorDTO.getNumeratorUnit().equals(CommonConstant.NUMERATOR_UNIT_KG)){
                realUnit = CommonConstant.NUMERATOR_UNIT_KG.substring(0,2);
            }else {
                realUnit = CommonConstant.NUMERATOR_UNIT_G.substring(0,1);
            }

            // 根据因子单位及气体id查询出对应的气体单位
            CyGasStoreUnit cyGasStoreUnit = cyGasStoreUnitMapper.selectUnitByGasIdAndUnit(cyGasStore.getId(), realUnit);

            if(cyGasStore != null && cyGasStoreUnit != null){
                // 构造气体对象
                CyHouseGas cyHouseGas = new CyHouseGas();
                // 设置气体名称
                cyHouseGas.setGasName(cyGasStore.getGasName());
                // 设置分子单位
                cyHouseGas.setMolecularUnit(cyGasStoreUnit.getGasUnit());
                // 设置分母单位
                cyHouseGas.setDenominatorUnit(emissionFactorDTO.getDenominatorUnit());
                // 设置gwp值
                cyHouseGas.setGwpValue(cyGasStore.getGwpValue());
                // 设置组织id
                cyHouseGas.setOrganizationId(emissionFactorDTO.getOrganizationId());
                // 设置部门id
                cyHouseGas.setDeptId(emissionFactorDTO.getDeptId());
                // 设置关联的因子id
                cyHouseGas.setEmissionFactorId(cyEmissionFactor.getId());
                // 设置因子值
                Double factorValue = Double.valueOf(emissionFactorDTO.getFactorValue());
                cyHouseGas.setFactorValue(BigDecimal.valueOf(factorValue));
                cyHouseGasService.save(cyHouseGas);
            }
        }
    }

    @Override
    public String addEmissionByCarbonCheck(EmissionFactorDTO emissionFactorDTO) {
        CyEmissionFactor cyEmissionFactor = new CyEmissionFactor();    //碳排因子信息对象
        if(emissionFactorDTO != null){
            BeanUtils.copyProperties(emissionFactorDTO, cyEmissionFactor);
            cyEmissionFactor.setOrganizationId(emissionFactorDTO.getOrganizationId());
            cyEmissionFactor.setDeptId(emissionFactorDTO.getDeptId());
//            设置默认发布状态为已发布，因为场景为因子添加后直接使用了，所以默认为发布
            cyEmissionFactor.setState("1");
            cyEmissionFactor.setDelFlag(0);
        }
        //将数据插入碳排因子表中  (需要用到返回的id)
        cyEmissionFactorMapper.add(cyEmissionFactor);

        CyEmissionFactorData cyEmissionFactorData = new CyEmissionFactorData();  //碳排因子数据详情对象
        if(emissionFactorDTO != null){
            BeanUtils.copyProperties(emissionFactorDTO, cyEmissionFactorData);
            cyEmissionFactor.setOrganizationId(emissionFactorDTO.getOrganizationId());
            cyEmissionFactor.setDeptId(emissionFactorDTO.getDeptId());
            //碳排因子数据对象中的计算类型字段为type，而DTO对象中传递的计算类型为computerType
            cyEmissionFactorData.setType(emissionFactorDTO.getComputerType());
            //碳排因子数据详情对象与碳排因子关联起来
            cyEmissionFactorData.setEmissionFactorId(cyEmissionFactor.getId());
        }
        //将数据插入碳排因子数据详情表中
        cyEmissionFactorDataService.save(cyEmissionFactorData);

        //计算类型为配比计算，就存入气体对象
        if(cyEmissionFactorData.getType().equals(2) || emissionFactorDTO.getGasList()!= null ){
            List<CyHouseGas> gasList = emissionFactorDTO.getGasList();
            for (CyHouseGas cyHouseGas : gasList) {
                //与碳排因子数据详情关联起来
                cyHouseGas.setEmissionFactorId(cyEmissionFactor.getId());
                //设置组织id和部门id
                cyHouseGas.setOrganizationId(emissionFactorDTO.getOrganizationId());
                cyHouseGas.setDeptId(emissionFactorDTO.getDeptId());
                cyHouseGasService.save(cyHouseGas);
            }

        }
        // 由于前端需要使用到当前新增因子的id，所以返回新增的id
        return cyEmissionFactor.getId();
    }

    /**
     *  查看详情
     *
     * @param id
     * @param
     * @return
     */
    @Override
    public EmissionFactorVO listInfo(java.lang.String id) {
        //构造vo对象
        EmissionFactorVO emissionFactorVO = new EmissionFactorVO();
        //查询碳排因子信息
        CyEmissionFactor cyEmissionFactor = cyEmissionFactorMapper.select(id);
        //查询碳排因子数据详情信息
        CyEmissionFactorData cyEmissionFactorData  = cyEmissionFactorDataService.SelectByEmissionFactorId(id);
        //查询碳排因子信息中的气体气体配比
        List<CyHouseGas> gasList = cyHouseGasService.getGasList(id);
        // 手动查询出字段对应的字典值
        if(cyEmissionFactor.getSourceType()!=null){
            String sourceTypeDict = cyEmissionFactorMapper.getSourceTypeDict("source_type", cyEmissionFactor.getSourceType());
            emissionFactorVO.setSourceTypeDict(sourceTypeDict);     // 来源类型字典值
        }
        if(cyEmissionFactor.getDocType()!=null){
            String documentTypeDict = cyEmissionFactorMapper.getDocTypeDict("document_type", cyEmissionFactor.getDocType());
            emissionFactorVO.setDocTypeDict(documentTypeDict);     // 文献类型字典值
        }
        if(cyEmissionFactor.getProductClassification()!=null){
            String productTypeDict = cyEmissionFactorMapper.getProductClassificationDict("product_type", cyEmissionFactor.getProductClassification());
            emissionFactorVO.setProductClassificationDict(productTypeDict);  // 产品分类字典值
        }

        if(cyEmissionFactor.getEmissionFactorDatabase()!=null){
            String emissionFactorDatabaseDict = cyEmissionFactorMapper.getProductClassificationDict("emission_factor_database", cyEmissionFactor.getEmissionFactorDatabase());
            emissionFactorVO.setEmissionFactorDatabaseDict(emissionFactorDatabaseDict);  // 因子库分类字典值
        }

        if(cyEmissionFactor.getGwpVersion()!=null){
            String gwpVersionDict = cyEmissionFactorMapper.getProductClassificationDict("emission_factor_gwp_version", cyEmissionFactor.getGwpVersion());
            emissionFactorVO.setGwpVersionDict(gwpVersionDict);  // gwp版本字典值
        }

        if(cyEmissionFactor.getCategory()!=null){
            String categoryDict = cyEmissionFactorMapper.getProductClassificationDict("emission_factor_category", cyEmissionFactor.getCategory());
            emissionFactorVO.setCategoryDict(categoryDict);  // 排放洗漱种类字典值
        }


        emissionFactorVO.setEmissionFactorObject(cyEmissionFactor);            //碳排因子
        emissionFactorVO.setEmissionFactorDataObject(cyEmissionFactorData);   //碳排因子数据详情
        emissionFactorVO.setGasList(gasList);                                 //碳排因子气体配比


        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();  //获取当前用户
        //查询出当前组织是否收藏过了这个碳排因子，用来设置收藏标致
        CyEmissionFactorCollect cyEmissionFactorCollect = cyEmissionFactorCollectMapper.selectCollectFactor(cyEmissionFactor.getId(), sysUser.getOrganizationId(), sysUser.getDeptId());
        if(cyEmissionFactorCollect !=null){
            //标示设置为已收藏
            emissionFactorVO.setCollectStatus("1");
        }else{
            emissionFactorVO.setCollectStatus("0");
        }

        //   如果没有存储碳排因子浏览记录的对象，就创建一个对象存储
        if(redisUtil.get(HISTORY_RECORD) == null){
            Map<String,Object> map = new LinkedHashMap<>();
            redisUtil.set(HISTORY_RECORD,map);
        }
        //获取到存储碳排因子浏览记录的对象
        Map<String,Object> historyRecordMap = (Map)redisUtil.get(HISTORY_RECORD);
        // 如果当前用户有这条浏览记录，就删除这条浏览记录，重新插入
        if(historyRecordMap.get(emissionFactorVO.getEmissionFactorObject().getId())!= null){
            JSONObject jsonObject = (JSONObject)historyRecordMap.get(emissionFactorVO.getEmissionFactorObject().getId());
                if(jsonObject.get("organizationId").equals(sysUser.getOrganizationId()) && jsonObject.get("deptId").equals(sysUser.getDeptId())){
                    historyRecordMap.remove(emissionFactorVO.getEmissionFactorObject().getId());
                }
        }
        //向碳排因子浏览记录对象中添加新的浏览记录对象
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("organizationId",sysUser.getOrganizationId());
        jsonObject.put("deptId",sysUser.getDeptId());
        //碳排因子id作为key，组织id和部门id作为value
        historyRecordMap.put(emissionFactorVO.getEmissionFactorObject().getId(),jsonObject);
        //更新碳排因子浏览记录对象
        redisUtil.set(HISTORY_RECORD,historyRecordMap);

        return emissionFactorVO;
    }

    @Override
    public List<EmissionFactorVO> batchListInfo(List<String> idList) {

        //结果集合
        List<EmissionFactorVO> resultList = new ArrayList<>();

        for (String id : idList) {
            //创建查询结果的vo对象
            EmissionFactorVO emissionFactorVO = new EmissionFactorVO();

            //查询出碳排因子对象
            CyEmissionFactor cyEmissionFactor = cyEmissionFactorMapper.select(id);
            //查询出碳排因子数据详情对象
            CyEmissionFactorData cyEmissionFactorData  = cyEmissionFactorDataService.SelectByEmissionFactorId(id);
            //查询出碳排因子气体配比对象
            List<CyHouseGas> gasList = cyHouseGasService.getGasList(id);
            //将数据封装在vo对象中
            emissionFactorVO.setEmissionFactorObject(cyEmissionFactor);
            emissionFactorVO.setEmissionFactorDataObject(cyEmissionFactorData);
            emissionFactorVO.setGasList(gasList);
            //将vo对象添加到结果集合当中
            resultList.add(emissionFactorVO);
        }


        //原本编写的批量查询详情接口，但是数据不能合理封装
//         List<EmissionFactorVO> emissionFactorVOS = cyEmissionFactorMapper.batchListInfo(idList);

        return resultList;
    }

    /**
     *  批量获取碳排因子主体信息（内部使用）
     */

    @Override
    public List<CyEmissionFactor> batchGetFactorInfo(List<String> idList) {
        List<CyEmissionFactor> cyEmissionFactorlist = cyEmissionFactorMapper.batchGetFactorInfo(idList);
        return cyEmissionFactorlist;
    }

    /**
     *  热门搜索因子
     *
     * @param SearchNum 查询数量
     * @param
     * @return
     */
    @Override
    public List<EmissionFactorQueryVO> topSearchFactor(String token,Integer SearchNum) {

        //获取到热门搜索因子的对象
        Map<String,Integer> hashMap = (Map) redisUtil.get(TOP_SEARCH_FACTOR);
        //获取到所有键值对，用于排序
        ArrayList<Map.Entry<String,Integer>> list = new ArrayList<>(hashMap.entrySet());

        Collections.sort(list, new Comparator<Map.Entry<String,Integer>>() {
            @Override
            //根据搜索次数进行降序排序
            public int compare(Map.Entry<String,Integer> o1, Map.Entry<String,Integer> o2) {
                return   (Integer)o2.getValue().compareTo((Integer)o1.getValue());
            }
        });
        //存储热门搜索因子的id
        List<String> idList = new ArrayList();

        //如果查询的数量大于热门搜索因子的数量，就置为热门搜索因子的总数（代表全查）
        if( SearchNum >list.size()){
            SearchNum = list.size();
        }
        //查询出所有缓存的热门搜索因子
        for(int i=0; i<list.size() ; i++){
            //获取到热门搜索因子的id，并且添加到集合中
            idList.add(list.get(i).getKey());
        }

        //由于前端展示的数据中包含了碳排因子-数据详情中的分子单位、分母单位、因子值，所以需要查询出这些数据，并且将数据封装到VO对象中
        //查询出所有热门搜索因子及相关的数据详情信息
        List<EmissionFactorQueryVO> emissionFactorQueryVOS = cyEmissionFactorMapper.topSearchFactor(idList,SearchNum);

        //如果没有传递token，则代表没有登录
        if(token == null || token == ""){
            //如果没有登录就设置收藏标致为0
            for (EmissionFactorQueryVO emissionFactorQueryVO : emissionFactorQueryVOS) {
                emissionFactorQueryVO.setCollectStatus("0");
            }
            return emissionFactorQueryVOS;
        }else{
            //如果传递了token，则解析token获取当前用户
            LoginUser loginUser = sysBaseApi.getUserByName(JwtUtil.getUsername(token));

            //如果当前登录了并且解析成功了，就设置对应的收藏标致
            if(loginUser!=null){
                String organizationId = loginUser.getOrganizationId();//当前用户的组织ID
                String deptId = loginUser.getDeptId();                //当前用户的部门ID
                //查询出当前组织下收藏的碳排因子
                List<CyEmissionFactorCollect> CollectList = cyEmissionFactorCollectMapper.selectCurrentOrganizationCollect(organizationId, deptId);

                //遍历所有的收藏记录，如果当前遍历到的记录的id等于当前遍历到的 CarbonFactorQueryVO的id，就设置收藏标致为1，否则为0
                //遍历所有最新发布因子
                for (EmissionFactorQueryVO emissionFactorQueryVO : emissionFactorQueryVOS) {
                    //默认设置所有收藏标致为0
                    emissionFactorQueryVO.setCollectStatus("0");
                    //遍历所有收藏记录
                    for (CyEmissionFactorCollect cyEmissionFactorCollect : CollectList) {
                        //如果最新发布因子的id等于收藏记录的碳排因子id，就将其收藏标致设置为1
                        if(emissionFactorQueryVO.getId().equals(cyEmissionFactorCollect.getEmissionFactorId())){
                            emissionFactorQueryVO.setCollectStatus("1");
                        }
                    }
                }
            }else{
                //如果解析失败就设置收藏标致为0
                for (EmissionFactorQueryVO emissionFactorQueryVO : emissionFactorQueryVOS) {
                    emissionFactorQueryVO.setCollectStatus("0");
                }
            }
        }

        return emissionFactorQueryVOS;
    }

    /**
     * 碳排因子首页列表查询中，不同行业类型返回的徽标数
     */
    @Override
    public Map<String,Integer> IndustryTypeBadge() {

        //获取到存储不同行业类型的徽标数对象
        Map<String,Integer> IndustryMap = (Map) redisUtil.get(EACH_INDUSTRY_FACTOR_NUMBER);

        return IndustryMap;
    }

    /**
     *  查询最新发布的因子
     *
     * @param Number  查询数量
     * @param
     * @return
     */
    @Override
    public List<EmissionFactorQueryVO> SelectNewPublishFactor(String token,Integer Number) {
        //查询出所有的最新发布的因子
        List<EmissionFactorQueryVO> emissionFactorQueryVOS = cyEmissionFactorMapper.SelectNewPublishFactor(Number);

        //如果没有传递token，则代表没有登录
        if(token == null || token == ""){
            //如果没有登录就设置收藏标致为0
            for (EmissionFactorQueryVO emissionFactorQueryVO : emissionFactorQueryVOS) {
                emissionFactorQueryVO.setCollectStatus("0");
            }
            return emissionFactorQueryVOS;
        }else{
            //如果传递了token，则解析token获取当前用户
            LoginUser loginUser = sysBaseApi.getUserByName(JwtUtil.getUsername(token));

            //如果当前登录了并且解析成功了，就设置对应的收藏标致
            if(loginUser!=null){
                String organizationId = loginUser.getOrganizationId();//当前用户的组织ID
                String deptId = loginUser.getDeptId();                //当前用户的部门ID
                //查询出当前组织下收藏的碳排因子
                List<CyEmissionFactorCollect> CollectList = cyEmissionFactorCollectMapper.selectCurrentOrganizationCollect(organizationId, deptId);

                //遍历所有的收藏记录，如果当前遍历到的记录的id等于当前遍历到的 CarbonFactorQueryVO的id，就设置收藏标致为1，否则为0
                //遍历所有最新发布因子
                for (EmissionFactorQueryVO emissionFactorQueryVO : emissionFactorQueryVOS) {
                    //默认设置所有收藏标致为0
                    emissionFactorQueryVO.setCollectStatus("0");
                    //遍历所有收藏记录
                    for (CyEmissionFactorCollect cyEmissionFactorCollect : CollectList) {
                        //如果最新发布因子的id等于收藏记录的碳排因子id，就将其收藏标致设置为1
                        if(emissionFactorQueryVO.getId().equals(cyEmissionFactorCollect.getEmissionFactorId())){
                            emissionFactorQueryVO.setCollectStatus("1");
                        }
                    }
                }
            }else{
                //如果解析失败就设置收藏标致为0
                for (EmissionFactorQueryVO emissionFactorQueryVO : emissionFactorQueryVOS) {
                    emissionFactorQueryVO.setCollectStatus("0");
                }
            }
        }
        return emissionFactorQueryVOS;
    }

    /**
     *  查询历史记录
     *
     * @return  resultList 历史查询过的碳排因子集合（最近五条）
     */
    @Override
    public List<EmissionFactorQueryVO> historyRecord() {

        // 存储碳排因子id集合
        List<String> idList = new ArrayList<String>();
        //获取当前用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //获取当前用户的组织id和部门id
        String organizationId = sysUser.getOrganizationId();
        String deptId = sysUser.getDeptId();
        //获取到存储浏览记录的对象
        Map<String,JSONObject> historyRecordMap = (Map) redisUtil.get(HISTORY_RECORD);

        // 存储查询结果的对象
        List<EmissionFactorQueryVO> emissionFactorQueryVOS =  new ArrayList<>();
        // 如果不为空，就遍历整个map查询对应因子，如果map为空，就返回空数组
        if(historyRecordMap!=null){
            //遍历整个map
            for (String key : historyRecordMap.keySet()) {
                //判断是否为当前用户的浏览记录
                JSONObject jsonObject = historyRecordMap.get(key);
                // 如果是当前用户的浏览记录，就存储这个因子的id
                if(jsonObject.getString("organizationId").equals(organizationId) && jsonObject.getString("deptId").equals(deptId)){
                    idList.add(key);
                }
            }

            if(idList.size()>5){
                // 拿出后五个浏览记录的因子id
                List<String> newIdList =  idList.subList(idList.size() - 5, idList.size());
                // 根据id，查询出因子信息
                emissionFactorQueryVOS = cyEmissionFactorMapper.batchGetFactor(newIdList);
                Collections.reverse(emissionFactorQueryVOS);
            }else{
                emissionFactorQueryVOS = cyEmissionFactorMapper.batchGetFactor(idList);
                Collections.reverse(emissionFactorQueryVOS);
            }

            //查询出当前组织的所有收藏因子
            List<CyEmissionFactorCollect> CollectList = cyEmissionFactorCollectMapper.selectCurrentOrganizationCollect(sysUser.getOrganizationId(), sysUser.getDeptId());
            //循环整个结果集合
            for (EmissionFactorQueryVO emissionFactorQueryVO : emissionFactorQueryVOS) {
                //默认设置所有收藏标致为未收藏
                emissionFactorQueryVO.setCollectStatus("0");
                //循环当前组织的收藏集合
                for (CyEmissionFactorCollect cyEmissionFactorCollect : CollectList) {
                    //如果收藏因子的id与当前查询到的id相同，则设置收藏标致为已收藏
                    if(cyEmissionFactorCollect.getEmissionFactorId().equals(emissionFactorQueryVO.getId())){
                        emissionFactorQueryVO.setCollectStatus("1");
                    }
                }
            }
        }
        return emissionFactorQueryVOS;
    }

    /**
     * 分页列表查询
     *
     * @param emissionFactorQueryDTO 分页列表查询对象
     * @param token 接口为放开的接口，所以传递token，适用于登录和不登录的两种情况。
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public Result<?> queryPageList(EmissionFactorQueryDTO emissionFactorQueryDTO, Integer pageNo, Integer pageSize, String token) {

        LoginUser loginUser = null;
        if(token!=null && token!=""){
            //如果传递了token，则解析token获取当前用户
            loginUser = sysBaseApi.getUserByName(JwtUtil.getUsername(token));
        }

        //如果没有传递type值，则默认查询碳排因子库
        if(emissionFactorQueryDTO.getType() == null || emissionFactorQueryDTO.getType() == ""){
            emissionFactorQueryDTO.setType("1");
        }else{
            //如果查询的是组织因子库，则需要获取当前用户的部门ID和组织ID
            if(emissionFactorQueryDTO.getType().equals("2")){
                if(loginUser !=null){
                    emissionFactorQueryDTO.setOrganizationId(loginUser.getOrganizationId());
                    emissionFactorQueryDTO.setDeptId(loginUser.getDeptId());
                }else{
                    //如果传递的token解析失败了，则返回错误信息，因为在得不到用户组织的情况下，不能查询组织因子库
                    return  Result.error("请传递正确的token");
                }
            }
        }
        Page<EmissionFactorQueryVO> page = new Page<EmissionFactorQueryVO>(pageNo, pageSize);
        IPage<EmissionFactorQueryVO> emissionFactorQueryVOIPage = cyEmissionFactorMapper.queryPageList(page, emissionFactorQueryDTO);

        //   首页放开的碳排因子库查询接口需要同时返回分页列表查询结果中对应行业类型的对应徽标数
        if(redisUtil.get(EACH_INDUSTRY_FACTOR_NUMBER) == null){
            //   如果没有存储行业因子数量的对象，就创建一个对象存储
            Map<String,Integer> map = new HashMap<>();
            redisUtil.set(EACH_INDUSTRY_FACTOR_NUMBER,map);
        }

        //获取到存储行业因子数量的对象
        Map<String,Integer> industryMap = (Map)redisUtil.get(EACH_INDUSTRY_FACTOR_NUMBER);
        //清除上一次的行业类型查询徽标数数据
        industryMap.clear();

        //如果是碳排因子库中的查询，需要展示查询结果中不同行业类型的徽标数，否则不执行以下操作
        if(emissionFactorQueryDTO.getType().equals("1")){
            //从分页列表查询中获取到查询到的数据
            for (EmissionFactorQueryVO emissionFactorQueryVO : emissionFactorQueryVOIPage.getRecords()) {
                //如果当前行业类型不存在，则新建一个键值对
                if(industryMap.get(emissionFactorQueryVO.getIndustryId()) == null){
                    industryMap.put(emissionFactorQueryVO.getIndustryId(),1);
                }else{
                    //否则将查询次数加1
                    industryMap.put(emissionFactorQueryVO.getIndustryId(),(Integer) industryMap.get(emissionFactorQueryVO.getIndustryId())+1);
                }
            }
            if(industryMap!=null){
                //更新redis中的数据
                redisUtil.set(EACH_INDUSTRY_FACTOR_NUMBER,industryMap);
            }
        }


        //碳排因子被查询的同时，需要增加对应的热门搜索因子次数
		if(redisUtil.get(TOP_SEARCH_FACTOR) == null){
            //如果没有就新建一个存储热门搜索因子的对象
			Map<String,Integer> map = new HashMap<>();
			redisUtil.set(TOP_SEARCH_FACTOR,map);
		}
        //获取到热门搜索因子的整体对象
        Map<String,Integer> map = (Map)redisUtil.get(TOP_SEARCH_FACTOR);

        //从分页对象中获取到查询到的数据
        List<EmissionFactorQueryVO> records = emissionFactorQueryVOIPage.getRecords();
        //将被查询到的数据添加到redis中（记录搜索次数）
        for (EmissionFactorQueryVO emissionFactorQueryVO : records) {
            //如果当前碳排因子不存在，则新建一个键值对
            if(map.get(emissionFactorQueryVO.getId()) == null){
                map.put(emissionFactorQueryVO.getId(),1);
            }else{
                //否则将查询次数加1
                map.put(emissionFactorQueryVO.getId(),(Integer) map.get(emissionFactorQueryVO.getId())+1);
            }
        }
		redisUtil.set(TOP_SEARCH_FACTOR,map);   //更新redis中的数据


        //如果当前用户登录了并且解析成功了，就设置对应的收藏标致
        if(loginUser!=null){
            String organizationId = loginUser.getOrganizationId();//当前用户的组织ID
            String deptId = loginUser.getDeptId();                //当前用户的部门ID
            //查询出当前组织下收藏的碳排因子
            List<CyEmissionFactorCollect> CollectList = cyEmissionFactorCollectMapper.selectCurrentOrganizationCollect(organizationId, deptId);

            //遍历所有的收藏记录，如果当前遍历到的记录的id等于当前遍历到的 CarbonFactorQueryVO的id，就设置收藏标致为1，否则为0
            for (EmissionFactorQueryVO emissionFactorQueryVO : emissionFactorQueryVOIPage.getRecords()) {
                //默认设置所有收藏标致为0
                emissionFactorQueryVO.setCollectStatus("0");
                //遍历所有收藏记录
                for (CyEmissionFactorCollect cyEmissionFactorCollect : CollectList) {
                    //如果当前查询到的碳排因子id与收藏因子id匹配，则设置收藏标致为1，代表已收藏
                    if(emissionFactorQueryVO.getId().equals(cyEmissionFactorCollect.getEmissionFactorId())){
                        emissionFactorQueryVO.setCollectStatus("1");
                    }
                }
            }
        }else{
            //如果token解析失败，代表未登录就设置所有因子的收藏标致为0，代表未收藏
            for (EmissionFactorQueryVO emissionFactorQueryVO : emissionFactorQueryVOIPage.getRecords()) {
                emissionFactorQueryVO.setCollectStatus("0");
            }
        }
        return Result.ok(emissionFactorQueryVOIPage);

    }

    // 管理平台-碳排因子-分页列表查询
    @Override
    public Result<?> emissionQueryPageList(EmissionFactorQueryDTO emissionFactorQueryDTO, Integer pageNo, Integer pageSize) {
        Page<EmissionFactorQueryVO> page = new Page<EmissionFactorQueryVO>(pageNo, pageSize);
        IPage<EmissionFactorQueryVO> emissionFactorQueryVOIPage = cyEmissionFactorMapper.emissionQueryPageList(page, emissionFactorQueryDTO);
        return Result.ok(emissionFactorQueryVOIPage);
    }


    /**
     *  内部使用的分页列表查询（组织碳盘查和产品碳足迹模块使用）
     */
    @Override
    public IPage<EmissionFactorQueryVO> privateQueryPageList(PrivateFactorQueryDTO privateFactorQueryDTO, Integer pageNo, Integer pageSize) {
        Page<EmissionFactorQueryVO> page = new Page<EmissionFactorQueryVO>(pageNo, pageSize);

        //获取当前用户的组织ID和部门ID
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String organizationId = sysUser.getOrganizationId();
        String deptId = sysUser.getDeptId();

        privateFactorQueryDTO.setOrganizationId(organizationId);
        privateFactorQueryDTO.setDeptId(deptId);
        //查询出因子数据
        IPage<EmissionFactorQueryVO> emissionFactorQueryVOIPage = cyEmissionFactorMapper.privateQueryPageList(page, privateFactorQueryDTO);

        //查询出当前组织下收藏的碳排因子
        List<CyEmissionFactorCollect> CollectList = cyEmissionFactorCollectMapper.selectCurrentOrganizationCollect(organizationId, deptId);

        for (EmissionFactorQueryVO emissionFactorQueryVO : emissionFactorQueryVOIPage.getRecords()) {
            //默认设置所有收藏标致为0
            emissionFactorQueryVO.setCollectStatus("0");
            for (CyEmissionFactorCollect cyEmissionFactorCollect : CollectList) {
                //如果当前查询到的碳排因子id与收藏因子id匹配，则设置收藏标致为1
                if(emissionFactorQueryVO.getId().equals(cyEmissionFactorCollect.getEmissionFactorId())){
                    emissionFactorQueryVO.setCollectStatus("1");
                }
            }
        }

        return emissionFactorQueryVOIPage;
    }

    // 批量查询碳排因子使用说明对象
    @Override
    public List<EmissionFactorDescribeVO> describeList(List<String> idList) {
        //批量查询碳排因子使用说明对象
        List<EmissionFactorDescribeVO> emissionFactorDescribeVOS = cyEmissionFactorMapper.describeList(idList);
        return emissionFactorDescribeVOS;
    }

    /**
     *  碳排因子逻辑删除（组织因子库中使用）
     */
    @Override
    public void logicDeleteById(String id) {
        Integer delFlag = 1;
        cyEmissionFactorMapper.logicDeleteById(id,delFlag);
    }


    /**
     *  查询碳排因子创建人接口
     */
    @Override
    public List<String> getCreatePeople() {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();  //获取当前用户
        String organizationId = sysUser.getOrganizationId();
        String deptId = sysUser.getDeptId();
        //查询出当前组织下的所有用户
        List<String> people = cyEmissionFactorMapper.getCreatePeople(organizationId, deptId);
        return people;
    }

    @Override
    @Transactional
    public void updateEmissionFactor(EmissionFactorDTO emissionFactorDTO) {
        //碳排因子信息对象
        CyEmissionFactor cyEmissionFactor = new CyEmissionFactor();
        if(emissionFactorDTO != null){
            BeanUtils.copyProperties(emissionFactorDTO, cyEmissionFactor);
        }
        //更新碳排因子信息  (需要用到返回的id)
        cyEmissionFactorMapper.updateById(cyEmissionFactor);

        //碳排因子数据详情对象
        CyEmissionFactorData cyEmissionFactorData = new CyEmissionFactorData();
        if(emissionFactorDTO != null){
            BeanUtils.copyProperties(emissionFactorDTO, cyEmissionFactorData);
            //碳排因子数据对象中的计算类型字段为type，而DTO对象中传递的计算类型为computerType
            cyEmissionFactorData.setType(emissionFactorDTO.getComputerType());
            //碳排因子数据详情对象与碳排因子关联起来
            cyEmissionFactorData.setEmissionFactorId(cyEmissionFactor.getId());
        }
        // 更新碳排因子数据详情对象
        cyEmissionFactorDataService.updateByEmissionFactorId(cyEmissionFactorData);

        //计算类型为配比计算，就编辑气体对象列表
        if(cyEmissionFactorData.getType().equals(2) || emissionFactorDTO.getGasList()!= null ){
            List<CyHouseGas> gasList = emissionFactorDTO.getGasList();
            for (CyHouseGas cyHouseGas : gasList) {
                //与碳排因子关联起来
                cyHouseGas.setEmissionFactorId(cyEmissionFactor.getId());
                //设置组织id和部门id
                cyHouseGas.setOrganizationId(emissionFactorDTO.getOrganizationId());
                cyHouseGas.setDeptId(emissionFactorDTO.getDeptId());
            }
            // 将所有气体配比删除后重新插入
            cyHouseGasService.deleteByEmissionFactorId(cyEmissionFactor.getId());
            for (CyHouseGas cyHouseGas : gasList) {
                cyHouseGasService.save(cyHouseGas);
            }
        }
    }

    @Override
    public List<CyIndustryCategory> industryCategory() {
        String pid= INDUSTRY_CATEGORY_PID;
        //查询碳排因子行业分类
        List<CyIndustryCategory> cyIndustryCategories = cyEmissionFactorMapper.industryCategory(pid);
        return cyIndustryCategories;
    }

    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    @Override
    public void crawlData() {
        JSONObject areaGwpDatabase = areaGwpDatabase();
        JSONArray areaArray = areaGwpDatabase.getJSONArray("area");

        //获取因子单位
        List<CyEmissionUnit> allUnit = cyEmissionUnitService.getAllUnit();

        List<CyEmissionFactor> emissionFactorList = new ArrayList<>();
        List<CyEmissionFactorData> emissionFactorDateList = new ArrayList<>();
        List<CyHouseGas> houseGasList =  new ArrayList<>();

        // 因子库数据库
        List<DictModel> emissionFactorDatabase = sysBaseApi.queryEnableDictItemsByCode("emission_factor_database");
        for (DictModel dictModel : emissionFactorDatabase) {
            JSONArray list = getList(dictModel.getValue());
            // Step.1 组装查询条件
            for (int i = 0; i < list.size(); i++) {
                Object o = list.get(i);
                JSONObject jsonObject = JSONObject.parseObject(o.toString());
                String id = jsonObject.getString("id");
                JSONObject byId = getById(id);
                CirsEmissionFactorDTO emissionFactorDTO =  JSONObject.toJavaObject(byId, CirsEmissionFactorDTO.class);

                //组装因子对象
                String emissionFactorId = IdWorker.getIdStr();
                CyEmissionFactor cyEmissionFactor = new CyEmissionFactor();
                cyEmissionFactor.setEmissionFactorDatabase(dictModel.getValue());
                cyEmissionFactor.setGwpVersion(emissionFactorDTO.getGwpVersion());
                cyEmissionFactor.setCategory(emissionFactorDTO.getCategory());
                cyEmissionFactor.setId(emissionFactorId);
                cyEmissionFactor.setType("1");
                cyEmissionFactor.setName(emissionFactorDTO.getEmissionSource());
                cyEmissionFactor.setProductClassification(emissionFactorDTO.getEmissionSourceForm());
                cyEmissionFactor.setScene(emissionFactorDTO.getEventFacility());
                cyEmissionFactor.setReleaseOrg(dictModel.getText());
                if (emissionFactorDTO.getYear() != null){
                    cyEmissionFactor.setReleaseYear(emissionFactorDTO.getYear().toString());
                }
                String area = emissionFactorDTO.getArea();


                for (Object object : areaArray) {
                    JSONObject jsonObject2 = JSONObject.parseObject(object.toString());
                    String areaId = jsonObject2.getString("id");
                    if (area.equals(areaId)){
                        String ownership = jsonObject2.getString("name");
                        if (ownership.equals("台湾")){
                            cyEmissionFactor.setOwnership("中国台湾");
                        }else {
                            cyEmissionFactor.setOwnership(jsonObject2.getString("name"));
                        }
                        break;
                    }
                }
                cyEmissionFactor.setSourceType(cyEmissionFactor.getOwnership().equals("全球")?"1":"2");



                // 获取当前请求用户
                LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                cyEmissionFactor.setOrganizationId(sysUser.getOrganizationId());   //当前用户的组织ID
                cyEmissionFactor.setDeptId(sysUser.getDeptId());
                cyEmissionFactor.setState("1");
                emissionFactorList.add(cyEmissionFactor);

                //组装因子详情对象
                CyEmissionFactorData cyEmissionFactorData = new CyEmissionFactorData();
                cyEmissionFactorData.setEmissionFactorId(emissionFactorId);
                cyEmissionFactorData.setNumeratorUnit("kgCO2e");
                cyEmissionFactorData.setNumeratorUnitId("2");

                //判断系统中是否有此单位
                Optional<CyEmissionUnit> first = allUnit.stream().filter(unit -> unit.getUnitCode().equals(emissionFactorDTO.getActivityDataUnit())).findFirst();
                if (first.isPresent()){
                    cyEmissionFactorData.setDenominatorUnit(first.get().getUnitCode());
                    cyEmissionFactorData.setDenominatorUnitId(first.get().getId());
                }else {
                    //新增一个单位
                    CyEmissionUnit cyEmissionUnit = new CyEmissionUnit();
                    cyEmissionUnit.setUnitCode(emissionFactorDTO.getActivityDataUnit());
                    cyEmissionUnitService.save(cyEmissionUnit);
                    cyEmissionFactorData.setDenominatorUnit(cyEmissionUnit.getUnitCode());
                    cyEmissionFactorData.setDenominatorUnitId(cyEmissionUnit.getId());
                    allUnit.add(cyEmissionUnit);
                }
                cyEmissionFactorData.setType("2");
                cyEmissionFactorData.setOrganizationId(sysUser.getOrganizationId());   //当前用户的组织ID
                cyEmissionFactorData.setDeptId(sysUser.getDeptId());

                List<CyHouseGas> onHouseGasList =  new ArrayList<>();

                //创建温室气体
                if (emissionFactorDTO.getCo2() != null && emissionFactorDTO.getCo2().compareTo(BigDecimal.ZERO)>0){
                    CyHouseGas co2 = new CyHouseGas();
                    co2.setGasName("二氧化碳(CO2)");
                    co2.setFactorValue(emissionFactorDTO.getCo2().setScale(4, RoundingMode.HALF_UP));
                    co2.setMolecularUnit("kgCO2");
                    co2.setDenominatorUnit(cyEmissionFactorData.getDenominatorUnit());
                    if (emissionFactorDTO.getCo2Gwp() != null) {
                        co2.setGwpValue(emissionFactorDTO.getCo2Gwp().setScale(4, RoundingMode.HALF_UP));
                    }
                    co2.setOrganizationId(sysUser.getOrganizationId());   //当前用户的组织ID
                    co2.setDeptId(sysUser.getDeptId());
                    co2.setEmissionFactorId(emissionFactorId);
                    onHouseGasList.add(co2);
                }

                if (emissionFactorDTO.getN2o() != null && emissionFactorDTO.getN2o().compareTo(BigDecimal.ZERO)>0){
                    CyHouseGas n2o = new CyHouseGas();
                    n2o.setGasName("氧化亚氮(N2O)");
                    n2o.setFactorValue(emissionFactorDTO.getN2o().setScale(4, RoundingMode.HALF_UP));
                    n2o.setMolecularUnit("kgN2O");
                    n2o.setDenominatorUnit(cyEmissionFactorData.getDenominatorUnit());
                    if (emissionFactorDTO.getN2oGwp() != null) {
                        n2o.setGwpValue(emissionFactorDTO.getN2oGwp().setScale(4, RoundingMode.HALF_UP));
                    }
                    n2o.setOrganizationId(sysUser.getOrganizationId());   //当前用户的组织ID
                    n2o.setDeptId(sysUser.getDeptId());
                    n2o.setEmissionFactorId(emissionFactorId);
                    onHouseGasList.add(n2o);
                }

                if (emissionFactorDTO.getCh4() != null && emissionFactorDTO.getCh4().compareTo(BigDecimal.ZERO)>0){
                    CyHouseGas ch4 = new CyHouseGas();
                    ch4.setGasName("甲烷(CH4)");
                    ch4.setFactorValue(emissionFactorDTO.getCh4().setScale(4, RoundingMode.HALF_UP));
                    ch4.setMolecularUnit("kgCH4");
                    ch4.setDenominatorUnit(cyEmissionFactorData.getDenominatorUnit());
                    if (emissionFactorDTO.getCh4Gwp() != null){
                        ch4.setGwpValue(emissionFactorDTO.getCh4Gwp().setScale(4, RoundingMode.HALF_UP));
                    }
                    ch4.setOrganizationId(sysUser.getOrganizationId());   //当前用户的组织ID
                    ch4.setDeptId(sysUser.getDeptId());
                    ch4.setEmissionFactorId(emissionFactorId);
                    onHouseGasList.add(ch4);
                }

                if (emissionFactorDTO.getHfcs() != null && emissionFactorDTO.getHfcs().compareTo(BigDecimal.ZERO)>0){
                    CyHouseGas hfcs = new CyHouseGas();
                    hfcs.setGasName("氢氟碳化合物(HFCs)");
                    hfcs.setFactorValue(emissionFactorDTO.getHfcs().setScale(4, RoundingMode.HALF_UP));
                    hfcs.setMolecularUnit("kgHFCs");
                    hfcs.setDenominatorUnit(cyEmissionFactorData.getDenominatorUnit());
                    if (emissionFactorDTO.getHfcsGwp() != null) {
                        hfcs.setGwpValue(emissionFactorDTO.getHfcsGwp().setScale(4, RoundingMode.HALF_UP));
                    }
                    hfcs.setOrganizationId(sysUser.getOrganizationId());   //当前用户的组织ID
                    hfcs.setDeptId(sysUser.getDeptId());
                    hfcs.setEmissionFactorId(emissionFactorId);
                    onHouseGasList.add(hfcs);
                }

                if (emissionFactorDTO.getSf6() != null && emissionFactorDTO.getSf6().compareTo(BigDecimal.ZERO)>0){
                    CyHouseGas sf6 = new CyHouseGas();
                    sf6.setGasName("六氟化硫(SF6)");
                    sf6.setFactorValue(emissionFactorDTO.getSf6().setScale(4, RoundingMode.HALF_UP));
                    sf6.setMolecularUnit("kgSF6");
                    sf6.setDenominatorUnit(cyEmissionFactorData.getDenominatorUnit());
                    if (emissionFactorDTO.getSf6Gwp() != null){
                        sf6.setGwpValue(emissionFactorDTO.getSf6Gwp().setScale(4, RoundingMode.HALF_UP));
                    }
                    sf6.setOrganizationId(sysUser.getOrganizationId());   //当前用户的组织ID
                    sf6.setDeptId(sysUser.getDeptId());
                    sf6.setEmissionFactorId(emissionFactorId);
                    onHouseGasList.add(sf6);
                }

                if (emissionFactorDTO.getNf3() != null && emissionFactorDTO.getNf3().compareTo(BigDecimal.ZERO)>0){
                    CyHouseGas nf3 = new CyHouseGas();
                    nf3.setGasName("三氟化氮(NF3)");
                    nf3.setFactorValue(emissionFactorDTO.getNf3().setScale(4, RoundingMode.HALF_UP));
                    nf3.setMolecularUnit("kgNF3");
                    nf3.setDenominatorUnit(cyEmissionFactorData.getDenominatorUnit());
                    if (emissionFactorDTO.getNf3Gwp() != null){
                        nf3.setGwpValue(emissionFactorDTO.getNf3Gwp().setScale(4, RoundingMode.HALF_UP));
                    }
                    nf3.setOrganizationId(sysUser.getOrganizationId());   //当前用户的组织ID
                    nf3.setDeptId(sysUser.getDeptId());
                    nf3.setEmissionFactorId(emissionFactorId);
                    onHouseGasList.add(nf3);
                }

                if (emissionFactorDTO.getPfcs() != null && emissionFactorDTO.getPfcs().compareTo(BigDecimal.ZERO)>0){
                    CyHouseGas pfcs = new CyHouseGas();
                    pfcs.setGasName("全氟碳化合物(PFCs)");
                    pfcs.setFactorValue(emissionFactorDTO.getPfcs().setScale(4, RoundingMode.HALF_UP));
                    pfcs.setMolecularUnit("kgPFCs");
                    pfcs.setDenominatorUnit(cyEmissionFactorData.getDenominatorUnit());
                    if (emissionFactorDTO.getPfcsGwp() != null){
                        pfcs.setGwpValue(emissionFactorDTO.getPfcsGwp().setScale(4, RoundingMode.HALF_UP));
                    }

                    pfcs.setOrganizationId(sysUser.getOrganizationId());   //当前用户的组织ID
                    pfcs.setDeptId(sysUser.getDeptId());
                    pfcs.setEmissionFactorId(emissionFactorId);
                    onHouseGasList.add(pfcs);
                }
                //计算二氧化碳当量
                BigDecimal co2Gwp = onHouseGasList.stream().map(item->
                        {
                            if (item.getFactorValue()!=null && item.getGwpValue()!=null){
                                return item.getFactorValue().multiply(item.getGwpValue());
                            }
                            return BigDecimal.ZERO;
                        }

                ).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(4, RoundingMode.HALF_UP);
                cyEmissionFactorData.setFactorValue(co2Gwp.toString());
                emissionFactorDateList.add(cyEmissionFactorData);
                houseGasList.addAll(onHouseGasList);
                System.out.println("执行到"+dictModel.getText()+"数据库 共"+list.size()+"条数据 当前是第"+i+"条");
            }
        }
        saveOrUpdateBatch(emissionFactorList);
        cyEmissionFactorDataService.saveOrUpdateBatch(emissionFactorDateList);
        cyHouseGasService.saveOrUpdateBatch(houseGasList);

    }


    public JSONObject areaGwpDatabase() {
        try {
            String URL = "https://carbon.cirs-group.com/api/carbon/rty/emission-source/area-gwp-database";
            String TOKEN = "bb9c99dd-07ba-4b79-86d3-d4167ed437f7";
            JSONObject jsonObject = doGetJson(URL,TOKEN);
            JSONObject jsonObject1 = jsonObject.getJSONObject("data");
            return jsonObject1;
        }catch (Exception e){
        }
        return null;
    }

    public JSONObject getById(String id) {
        try {
            String URL = "https://carbon.cirs-group.com/api/carbon/rty/emission-source/detail/"+id+"?id="+id;
            String TOKEN = "bb9c99dd-07ba-4b79-86d3-d4167ed437f7";
            JSONObject jsonObject = doGetJson(URL,TOKEN);
            JSONObject jsonObject1 = jsonObject.getJSONObject("data");
/*
            Set<String> strings = jsonObject1.keySet();
            for (String string : strings) {
                //将科学计数法转换为正常的数字
                Object o = jsonObject1.get(string);
                if (o instanceof BigDecimal){
                    BigDecimal decimalNumber = new BigDecimal(o.toString());
                    jsonObject1.put(string,decimalNumber.toPlainString());
                }
            }*/
            return jsonObject1;
        }catch (Exception e){

        }
        return null;
    }


    public JSONArray getList(String referenceSource) {
        try {
            String URL = "https://carbon.cirs-group.com/api/carbon/rty/emission-source/standard/list?referenceSource="+referenceSource+"&page=1&pageSize=2000";
            String TOKEN = "bb9c99dd-07ba-4b79-86d3-d4167ed437f7";
            JSONObject jsonObject = doGetJson(URL,TOKEN);
            JSONObject jsonObject1 = jsonObject.getJSONObject("data");
            JSONArray list = jsonObject1.getJSONArray("list");
            return list;
        }catch (Exception e){

        }
        return null;
    }

    /**
     * get请求 , 并接收 JSONObject 返回对象
     * @param URL 请求的url
     * @return
     * @throws IOException
     */
    public static JSONObject doGetJson(String URL,String TOKEN) throws IOException {
        JSONObject jsonObject = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        BufferedReader br = null;
        StringBuilder result = new StringBuilder();
        try {
            //创建远程url连接对象
            java.net.URL url = new URL(URL);
            //通过远程url连接对象打开一个连接，强转成HTTPURLConnection类
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(1500000);
            conn.setReadTimeout(6000000);
            conn.setRequestProperty("authorization", "bb9c99dd-07ba-4b79-86d3-d4167ed437f7");
            //发送请求
            conn.connect();
            //通过conn取得输入流，并使用Reader读取
            if (200 == conn.getResponseCode()) {
                is = conn.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String line;
                while ((line = br.readLine()) != null) {
                    result.append(line);
                }
            } else {
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            conn.disconnect();
        }
        jsonObject = JSONObject.parseObject(result.toString());
        return jsonObject;
    }
}
